<template>
  <div class="cdkey-management">
    <!-- 筛选表单 -->
    <el-card class="filter-card" style="margin-bottom: 20px;">
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item label="兑换码">
          <el-input v-model="filterForm.code" placeholder="请输入兑换码" clearable style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="渠道">
          <el-select v-model="filterForm.channel" placeholder="请选择渠道" clearable style="width: 150px;">
            <el-option
              v-for="item in channelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchData">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
          <el-button type="success" @click="handleAdd">新增兑换码</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>兑换码管理</span>
        <el-button 
          type="success" 
          size="small" 
          icon="el-icon-download"
          style="float: right;"
          @click="exportData"
          :loading="exportLoading">
          导出CSV
        </el-button>
      </div>

      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="code" label="兑换码" width="120" align="center"></el-table-column>
        <el-table-column prop="each_use_count" label="单用户使用次数" width="130" align="center">
          <template slot-scope="scope">
            {{ scope.row.each_use_count === -1 ? '无限制' : scope.row.each_use_count }}
          </template>
        </el-table-column>
        <el-table-column prop="used_count" label="已使用次数" width="100" align="center"></el-table-column>
        <el-table-column prop="total_count" label="总次数" width="80" align="center"></el-table-column>
        <el-table-column prop="expire_time" label="失效时间" width="150" align="center"></el-table-column>
        <el-table-column prop="award" label="奖励" width="120" align="center"></el-table-column>
        <el-table-column prop="uid" label="指定UID" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.uid === 0 ? '不限制' : scope.row.uid }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'info'">
              {{ scope.row.status === 0 ? '未使用' : '已使用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="vip_none" label="非VIP领取次数" width="120" align="center"></el-table-column>
        <el-table-column prop="vip" label="VIP领取次数" width="100" align="center"></el-table-column>
        <el-table-column prop="need_vip" label="VIP限制" width="80" align="center"></el-table-column>
        <el-table-column prop="exclusion" label="互斥" width="60" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.exclusion > 0 ? 'warning' : 'success'">
              {{ scope.row.exclusion > 0 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="channel" label="渠道" width="80" align="center"></el-table-column>
        <el-table-column prop="desc" label="备注" width="150" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="150" align="center"></el-table-column>
        <el-table-column label="操作" width="170" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px">
      <el-form :model="cdkeyForm" :rules="rules" ref="cdkeyForm" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="指定UID" prop="uid">
              <el-input-number v-model="cdkeyForm.uid" :min="0" placeholder="0表示不限制" style="width: 100%;" :controls="false"></el-input-number>
              <div class="form-tip">0：不限制 &gt;0：指定UID</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="渠道" prop="channel">
              <el-select v-model="cdkeyForm.channel" placeholder="请选择渠道" style="width: 100%;" clearable>
                <el-option
                  v-for="item in channelOptions.filter(option => option.value !== null)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 编辑时显示兑换码信息 -->
        <el-form-item v-if="isEdit" label="兑换码">
          <el-input v-model="cdkeyForm.code" placeholder="兑换码" style="width: 100%;" disabled></el-input>
          <div class="form-tip">兑换码不可编辑</div>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单用户使用次数" prop="each_use_count">
              <el-input-number v-model="cdkeyForm.each_use_count" :min="-1" placeholder="-1表示无限制" style="width: 100%;" :controls="false"></el-input-number>
              <!-- <div class="form-tip">-1：无限制</div> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="兑换码个数" prop="total_count">
              <el-input-number v-model="cdkeyForm.total_count" :min="1" placeholder="请输入兑换码个数" style="width: 100%;" :controls="false" :disabled="isEdit"></el-input-number>
              <div class="form-tip" v-if="isEdit">编辑时不可修改</div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="失效时间" prop="expire_time">
          <el-date-picker
            v-model="cdkeyForm.expire_time"
            type="datetime"
            placeholder="请选择失效时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item label="奖励内容" prop="award">
          <el-input v-model="cdkeyForm.award" placeholder="请输入奖励，例如：1000" style="width: 100%;"></el-input>
          <div class="form-tip">奖励</div>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="非VIP累计领取次数" prop="vip_none">
              <el-input-number v-model="cdkeyForm.vip_none" :min="0" placeholder="次数" style="width: 100%;" :controls="false"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="VIP累计领取次数" prop="vip">
              <el-input-number v-model="cdkeyForm.vip" :min="0" placeholder="次数" style="width: 100%;" :controls="false"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="领取VIP限制" prop="need_vip">
              <el-input-number v-model="cdkeyForm.need_vip" :min="0" placeholder="VIP等级" style="width: 100%;" :controls="false"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="是否互斥" prop="exclusion">
          <el-radio-group v-model="cdkeyForm.exclusion">
            <el-radio :label="0">不互斥</el-radio>
            <el-radio :label="1">互斥</el-radio>
          </el-radio-group>
          <div class="form-tip">当天领过其它码，就不能领这个意思</div>
        </el-form-item>
        
        <el-form-item label="备注" prop="desc">
          <el-input type="textarea" v-model="cdkeyForm.desc" placeholder="请输入备注信息" :rows="3" style="width: 100%;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">{{ isEdit ? '保存' : '确定' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { cdkeyList, cdkeyAdd, cdkeyEdit, cdkeyDelete } from '@/api/user'
import { exportDataToCsv } from '@/utils/export'
import channelMixin from '@/mixins/channelMixin'

export default {
  name: 'CdkeyManagement',
  mixins: [channelMixin],
  data() {
    return {
      // 表格数据
      tableData: [],
      loading: false,
      exportLoading: false,
      
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 筛选表单
      filterForm: {
        code: '',
        channel: null
      },


      dialogVisible: false,
      dialogTitle: '新增兑换码',
      isEdit: false,
      // 兑换码表单
      cdkeyForm: {
        id: null,
        code: '',
        uid: 0,
        channel: null,
        each_use_count: 1,
        total_count: 1,
        expire_time: '',
        award: '',
        vip_none: 0,
        vip: 0,
        need_vip: 0,
        exclusion: 0,
        desc: ''
      },
      
      // 表单验证规则
      rules: {
        limit_count: [
          { required: true, message: '请输入单用户使用次数', trigger: 'blur' }
        ],
        total_count: [
          { required: true, message: '请输入兑换码个数', trigger: 'blur' }
        ],
        expire_time: [
          { required: true, message: '请选择失效时间', trigger: 'change' }
        ],
        award: [
          { required: true, message: '请输入奖励内容', trigger: 'blur' }
        ],
        channel: [
          { required: true, message: '请选择渠道', trigger: 'change' }
        ]
      }
    }
  },
  
  async mounted() {
    this.fetchData()
  },

  methods: {
    async fetchData() {
      this.loading = true
      try {
        const data = {
          code: this.filterForm.code || '',
          channel: this.formatChannelParam(this.filterForm.channel),
          page: this.currentPage,
          page_size: this.pageSize
        }
        
        const response = await cdkeyList(data)
        
        if (response.code === 0) {
          this.tableData = response.data.cdkeys || []
          this.total = response.data.total || 0
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取兑换码列表失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    
    searchData() {
      this.currentPage = 1
      this.fetchData()
    },
    
    resetFilter() {
      this.filterForm = {
        code: '',
        channel: null
      }
      this.searchData()
    },
    
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchData()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增兑换码'
      this.cdkeyForm = {
        uid: 0,
        channel: null,
        each_use_count: 1,
        total_count: 1,
        expire_time: '',
        award: '',
        vip_none: 0,
        vip: 0,
        need_vip: 0,
        exclusion: 0,
        desc: ''
      }
      this.dialogVisible = true
      // 清除表单验证
      this.$nextTick(() => {
        this.$refs.cdkeyForm && this.$refs.cdkeyForm.clearValidate()
      })
    },
    
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑兑换码'
      this.cdkeyForm = {
        id: row.id,
        code: row.code,
        uid: row.uid || 0,
        channel: row.channel || 0,
        each_use_count: row.each_use_count || 1,
        total_count: row.total_count || 1,
        expire_time: row.expire_time || '',
        award: row.award || '',
        vip_none: row.vip_none || 0,
        vip: row.vip || 0,
        need_vip: row.need_vip || 0,
        exclusion: row.exclusion || 0,
        desc: row.desc || ''
      }
      this.dialogVisible = true
      // 清除表单验证
      this.$nextTick(() => {
        this.$refs.cdkeyForm && this.$refs.cdkeyForm.clearValidate()
      })
    },
    
    handleDelete(row) {
      this.$confirm(`确认删除兑换码 ${row.code}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await cdkeyDelete({ code: row.code })
          if (response.code === 0) {
            this.$message.success('删除成功')
            this.fetchData()
          } else {
            this.$message.error(response.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除兑换码失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        // 取消删除
      })
    },
    
    async submitForm() {
      this.$refs.cdkeyForm.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            let params
            let response
            
            if (this.isEdit) {
              // 修改接口参数 - 字段名有差异，需要特殊处理
              params = {
                id: this.cdkeyForm.id,
                code: this.cdkeyForm.code,
                uid: parseInt(this.cdkeyForm.uid) || 0,
                limit_count: parseInt(this.cdkeyForm.each_use_count) || 1, // 注意字段名差异
                total_count: parseInt(this.cdkeyForm.total_count) || 1,
                expire_time: this.cdkeyForm.expire_time,
                award: this.cdkeyForm.award,
                need_vip: parseInt(this.cdkeyForm.need_vip) || 0,
                vip_none: parseInt(this.cdkeyForm.vip_none) || 0,
                vip: parseInt(this.cdkeyForm.vip) || 0,
                exclusion: parseInt(this.cdkeyForm.exclusion) || 0
              }
              response = await cdkeyEdit(params)
            } else {
              // 新增接口参数 - 不包含id和code字段
              params = {
                uid: parseInt(this.cdkeyForm.uid) || 0,
                channel: this.formatChannelParam(this.cdkeyForm.channel),
                each_use_count: parseInt(this.cdkeyForm.each_use_count) || 1,
                total_count: parseInt(this.cdkeyForm.total_count) || 1,
                expire_time: this.cdkeyForm.expire_time,
                award: this.cdkeyForm.award,
                vip_none: parseInt(this.cdkeyForm.vip_none) || 0,
                vip: parseInt(this.cdkeyForm.vip) || 0,
                need_vip: parseInt(this.cdkeyForm.need_vip) || 0,
                exclusion: parseInt(this.cdkeyForm.exclusion) || 0,
                desc: this.cdkeyForm.desc || ''
              }
              response = await cdkeyAdd(params)
            }
            
            console.log('提交参数:', params)
            console.log('接口响应:', response)
            
            if (response && response.code === 0) {
              this.$message.success(this.isEdit ? '编辑成功' : '新增成功')
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(response.msg || response.message || (this.isEdit ? '编辑失败' : '新增失败'))
            }
          } catch (error) {
            console.error('提交失败:', error)
            this.$message.error(this.isEdit ? '编辑失败' : '新增失败')
          } finally {
            this.submitLoading = false
          }
        } else {
          return false
        }
      })
    },

    async exportData() {
      this.exportLoading = true
      try {
        const data = {
          code: this.filterForm.code || '',
          channel: this.formatChannelParam(this.filterForm.channel),
          page: 1,
          page_size: 10000
        }
        
        const response = await cdkeyList(data)
        const allData = response.data.cdkeys || []
        
        const columns = [
          { prop: 'id', label: 'ID' },
          { prop: 'code', label: '兑换码' },
          { prop: 'each_use_count', label: '单用户使用次数', formatter: (row) => row.each_use_count === -1 ? '无限制' : row.each_use_count },
          { prop: 'used_count', label: '已使用次数' },
          { prop: 'total_count', label: '总次数' },
          { prop: 'expire_time', label: '失效时间' },
          { prop: 'award', label: '奖励' },
          { prop: 'uid', label: '指定UID', formatter: (row) => row.uid === 0 ? '不限制' : row.uid },
          { prop: 'status', label: '状态', formatter: (row) => row.status === 0 ? '未使用' : '已使用' },
          { prop: 'vip_none', label: '非VIP领取次数' },
          { prop: 'vip', label: 'VIP领取次数' },
          { prop: 'need_vip', label: 'VIP限制' },
          { prop: 'exclusion', label: '互斥', formatter: (row) => row.exclusion > 0 ? '是' : '否' },
          { prop: 'channel', label: '渠道' },
          { prop: 'desc', label: '备注' },
          { prop: 'create_time', label: '创建时间' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `兑换码管理_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    }
  }
}
</script>

<style scoped>
.cdkey-management {
  padding: 20px 0;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}

.form-tip {
  font-size: 0.8em;
  color: #909399;
  margin-top: 5px;
}
</style> 